package org.swim.servlet;

import java.io.IOException;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.swim.entity.Ability;
import org.swim.session.AbilityManagerRemote;


/**
 * Servlet implementation class AddAbility
 */
public class AddAbility extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddAbility() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
		request.getRequestDispatcher("WEB-INF/AddAbility.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        	String abilityToAdd = request.getParameter("abilityToAdd");
            if (abilityToAdd.length()>0) {
	        	InitialContext ic;
	            try {
	    			ic = new InitialContext();
	    			AbilityManagerRemote abilityManager = (AbilityManagerRemote)ic.lookup("AbilityManagerRemote");
	    			List<Ability> abilities = abilityManager.getAllDefinedAbility();
	    			request.setAttribute("abilities", abilities);
	    			for(Ability current:abilities) {
	    				if(current.getNome().equals(abilityToAdd)) {
	    					throw new NullPointerException();
	    				}
	    			}
	    			abilityManager.defineNewAbility(abilityToAdd);
	    			List<Ability> abilitiestoSend = abilityManager.getAllDefinedAbility();
	    			request.setAttribute("abilities", abilitiestoSend);
	    			request.setAttribute("errors", "ok");
		           } catch (NamingException e) {
		    			e.printStackTrace();
		    		}  catch (NullPointerException e) { 
					request.setAttribute("errors", "abilityAlreadyExists");
		        } 
            } else {
				request.setAttribute("errors", "noAbility");          
            }
		request.getRequestDispatcher("WEB-INF/ManageAbilities.jsp").forward(request, response);
	}

}
